<!-- 用户管理 -->
<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <el-col>
      <div v-if="isShowSearchBtn" class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="关键字" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="微信号/昵称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="状态" prop="is_black">
            <el-select
              v-model="queryParams.is_black"
              placeholder="全部"
              clearable
              class="!w-[100px]"
            >
              <el-option label="已拉黑" value="1" />
              <el-option label="未拉黑" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="关注时间">
            <el-date-picker
              class="!w-[240px]"
              v-model="dateTimeRange"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery"
              ><i-ep-search />搜索</el-button
            >
            <el-button @click="resetQuery">
              <i-ep-refresh />
              重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never" class="table-container">
        <template #header>
          <div class="flex justify-between">
            <div>
              <el-button
                v-hasPerm="['wechatuser@black']"
                type="danger"
                v-if="ids.length > 0"
                @click="handleBlack()"
                ><i-ep-delete />拉黑/取消拉黑</el-button
              >
            </div>
            <div>
              <el-button
                class="ml-3"
                @click="handleSearchShowBtn"
                icon="Search"
                circle
              />
              <el-button
                class="ml-3"
                title="刷新"
                @click="handleQuery"
                icon="Refresh"
                circle
              />
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="pageData"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            key="id"
            sortable="custom"
            label="ID"
            align="center"
            prop="id"
            width="80"
          />
          <el-table-column
            label="昵称"
            width="120"
            align="center"
            prop="nickname"
          />
          <el-table-column
            label="微信号"
            width="240"
            align="center"
            prop="openid"
          />

          <el-table-column
            label="性别"
            width="100"
            align="center"
            prop="genderLabel"
          />
          <el-table-column label="是否关注" align="center">
            <template #default="scope">
              <el-tag
                v-if="scope.row.subscribe === 1"
                effect="dark"
                type="success"
                >已关注</el-tag
              >
              <el-tag
                v-if="scope.row.subscribe === 0"
                effect="dark"
                type="danger"
                >未关注</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column label="关注时间" width="160" prop="subscribe_time" />
          <el-table-column label="备注" prop="remark" />

          <el-table-column label="是否拉黑" align="center">
            <template #default="scope">
              <el-tag
                v-if="scope.row.is_black === 1"
                effect="dark"
                type="danger"
                >已拉黑</el-tag
              >
              <el-tag
                v-if="scope.row.is_black === 0"
                effect="dark"
                type="success"
                >未拉黑</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="同步时间" width="160" prop="created_at" />

          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                v-hasPerm="['wechatuser@remark']"
                title="设置备注"
                icon="Edit"
                circle
                type="primary"
                @click="openDialog(scope.row)"
              />
              <el-button
                v-if="scope.row.is_black === 0"
                v-hasPerm="['wechatuser@black']"
                title="拉黑"
                @click="handleBlack(scope.row.id)"
                icon="CircleClose"
                circle
                type="danger"
              />
              <el-button
                v-if="scope.row.is_black === 1"
                @click="handleBlack(scope.row.id)"
                v-hasPerm="['wechatuser@black']"
                title="取消拉黑"
                icon="CircleCheck"
                circle
                type="success"
              />
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.p"
          v-model:limit="queryParams.limit"
          @pagination="handleQuery"
        />
      </el-card>
    </el-col>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="openId" prop="openid">
          <span>{{ formData.openid }}</span>
        </el-form-item>
        <el-form-item label="用户名" prop="remark">
          <el-input
            v-model="formData.remark"
            :readonly="!!formData.id"
            placeholder="请输入用户名"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import { fetchList, updateMark, black } from "@/api/wechat";
import {
  WechatUser,
  WechatUserQuery,
  WechatUserForm,
} from "@/api/wechat/types";

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const isShowSearchBtn = ref(false);
const loading = ref(false); //  加载状态
const ids = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<WechatUserQuery>({
  p: 1,
  limit: 10,
});
const dateTimeRange = ref(""); //时间范围
const total = ref(0); // 数据总数
const pageData = ref<WechatUser[]>(); // 用户分页数据

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<WechatUserForm>({});

// 校验规则
const rules = reactive({
  remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  fetchList(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.p = 1;
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 排序 */
function handleSortChange(data: any) {
  const { prop, order } = data;
  if (prop === "id") {
    if (order === "ascending") {
      queryParams.sort = "+id";
    } else {
      queryParams.sort = "-id";
    }
    handleQuery();
  }
}

/**
 * 打开弹窗
 *
 * @param row 用户数据
 */
async function openDialog(row: WechatUser) {
  dialog.visible = true;
  dialog.title = "修改用户";
  Object.assign(formData, { ...row });
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
  handleQuery();
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      updateMark(formData)
        .then(() => {
          ElMessage.success("操作成功");
          closeDialog();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除用户 */
function handleBlack(id?: number) {
  const userIds = id || ids.value;
  if (!userIds) {
    ElMessage.warning("请勾选数据");
    return;
  }
  const data = {
    ids: userIds,
  };
  ElMessageBox.confirm("确认要操作的数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    black(data).then(() => {
      handleQuery();
      ElMessage.success("操作成功");
      handleQuery();
    });
  });
}

function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

onMounted(() => {
  handleQuery();
});
</script>
